<template>
  <div class="login">
    <Navbar></Navbar>

    <van-row justify="center">
      <van-col span="10">
        <h3>开始准备好好学习</h3>
      </van-col>
    </van-row>
    <van-row justify="center">
      <van-col span="10">
        <p>好好学习，做前端达人</p>
      </van-col>
    </van-row>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="confirmPassword"
          type="password"
          name="confirmPassword"
          label="确认密码"
          placeholder="确认密码"
          :rules="[{ required: true, message: '请确认密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          注册
        </van-button>
      </div>
    </van-form>

    <van-row justify="center">
      <van-col span="10">
        <router-link to="/login">返回登录页</router-link>
      </van-col>
    </van-row>

    <Tabbar></Tabbar>
  </div>
</template>

<script setup>
import Navbar from "@/components/Navbar.vue";
import Tabbar from "@/components/Tabbar.vue";
import axios from "axios";
import { ref } from "vue";
import { showSuccessToast, showFailToast } from 'vant';

const username = ref("");
const password = ref("");
const confirmPassword = ref("");

function onSubmit() {
  const userCount = ref(0);
  axios
    .get("http://localhost:3000/users?username=" + username.value)
    .then((result) => {
      // userCount.value = result.data.length;
      // 验证用户名是否存在
      if (result.data.length > 0) {
        showFailToast("用户名已存在");
        return;
      } else {
        // 验证两次密码是否一致
        if (password.value !== confirmPassword.value) {
          showFailToast("两次密码不一致");
          return;
        }

        const requestBody = {
          // id: (userCount.value + 1).toString(),
          username: username.value,
          password: password.value,
        };

        axios
          .post("http://localhost:3000/users", requestBody)
          .then((result) => {
            // 清空输入框得值
            username.value = "";
            password.value = "";
            confirmPassword.value = "";
            showSuccessToast('用户添加成功，请返回并登录');
          });
      }
    });
}
</script>

<style scoped>
</style>